package com.ruoyi.system.mybatis.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.system.mybatis.handler.TenantContextHolder;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.StringValue;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * Mybatis-plus 配置类
 *
 * @author Nottyjay
 * @since 2020-10-10
 */
@Configuration
@MapperScan("com.ruoyi.*.mapper")
public class MybatisConfig {

  /**
   * tenant_id 字段名
   */
  private static final String TENANT_FIELD_NAME = "tenant_id";
  /**
   * 哪些表需要做多租户 表需要添加一个字段 tenant_id
   */
  public static final List<String> tenantTable = new ArrayList<String>();
  static {
    tenantTable.add("sys_user");
    tenantTable.add("sys_role");
    tenantTable.add("sys_notice");
  }


  @Bean
  public MybatisPlusInterceptor mybatisPlusInterceptor() {
    MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
    interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() {
      @Override
      public Expression getTenantId() {
        try {
          Integer tenantId = TenantContextHolder.getTenantId();
          if (tenantId != 0) {
            return new LongValue(tenantId);
          }
          else
          {
            /* 用户未登陆时，返回缺省租户数据 */
            return new LongValue(0); // 用户未登录是，返回对账平台租户id：1001
          }
        } catch (Exception e) {
          /*异常时，返回缺省租户数据*/
          return new LongValue(0);
        }
      }

      @Override
      public String getTenantIdColumn(){
        return TENANT_FIELD_NAME;
      }

      // 返回 true 表示不走租户逻辑
      @Override
      public boolean ignoreTable(String tableName) {
        //判断是否为管理员 为管理员就不走租户
        if(Objects.nonNull(TenantContextHolder.getUserRole())) {
          if (TenantContextHolder.getUserRole().equals("admin")) {
            return true;
          }
        }
        for(String temp: tenantTable){
          if(temp.equalsIgnoreCase(tableName)){
            return false;
          }
        }
        return true;
      }
    }));
    interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
    interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
    return interceptor;
  }

}
